package org.yes.util;


import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * User: mtymes
 * Date: May 27, 2010
 * Time: 9:04:12 AM
 */
public class ReflectionUtil {

    /* ====================== */
    /* --- public methods --- */
    /* ====================== */


    public static List<Field> getDeclaredFields(final Class beanClass) {
        final List<Field> fields = new ArrayList<Field>();

        Class classToProcess = beanClass;
        do {
            fields.addAll(Arrays.asList(classToProcess.getDeclaredFields()));
            classToProcess = classToProcess.getSuperclass();
        } while (classToProcess != null);

        return fields;
    }


    public static List<Method> getMethods(final Class beanClass) {
        return Arrays.asList(beanClass.getMethods());
    }


    public static void setFieldValue(final Object bean, final Field field, final Object value) {
        boolean isAccessible = field.isAccessible();

        try {
            if (!isAccessible) {
                field.setAccessible(true);
            }

            try {
                field.set(bean, value);
            } catch (IllegalAccessException e) {
                throw new IllegalStateException(e);
            }

        } finally {
            if (!isAccessible) {
                field.setAccessible(isAccessible);
            }
        }
    }


    public static Object invokeMethod(final Object bean, final Method method, final Object... args) {
        try {

            return method.invoke(bean, args);

        } catch (IllegalAccessException e) {
            throw new IllegalStateException(e);
        } catch (InvocationTargetException e) {
            throw new IllegalStateException(e);
        }
    }
}
